﻿using B.S.BasicData.Domain;
using B.S.BasicData.ErrorCode;
using B.S.BasicData.Infrastructure.Interfance;
using B.S.BasicData.Read.Apilication.Common.User;
using B.S.BasicData.Read.DTOS;
using MediatR;

namespace B.S.BasicData.Read.Apilication.Handler.User
{
    public class GetUserHandler : IRequestHandler<GetUserCommon, ApiPaimg<UserDTO>>
    {
        private readonly IBaseRepository<UserModel> userrepo;
        private readonly IBaseRepository<ProvinceModel> provinceRepo;
        private readonly IBaseRepository<RoleModel> roleRepo;
        private readonly IBaseRepository<AccountRoleModel> accountroleModel;

        public GetUserHandler(IBaseRepository<UserModel> userrepo,IBaseRepository<ProvinceModel> provinceRepo,IBaseRepository<RoleModel> roleRepo,IBaseRepository<AccountRoleModel> accountroleModel)
        {
            this.userrepo = userrepo;
            this.provinceRepo = provinceRepo;
            this.roleRepo = roleRepo;
            this.accountroleModel = accountroleModel;
        }

        public Task<ApiPaimg<UserDTO>> Handle(GetUserCommon request, CancellationToken cancellationToken)
        {
            ApiPaimg<UserDTO> res = new ApiPaimg<UserDTO>();
            var user = userrepo.GetAll().Where(x=>x.IsDel==false);
            var province = provinceRepo.GetAll();
            var role = roleRepo.GetAll().Where(x => x.IsDeleted == false);
            var accountrole = accountroleModel.GetAll();



            //var linq = from a in user
            //           join b in province
            //           on a.provinceId equals b.provinceId
            //           join c in accountrole
            //           on a.UserId equals c.UserId
            //           join d in role
            //           on c.RoleId equals d.RoleId
            //           select new UserDTO()
            //           {
            //               UserId = a.UserId,
            //               UserName = a.UserName,
            //               PassWord = a.PassWord,
            //               Sex = a.Sex,
            //               provinceId = a.provinceId,
            //               provinceName = b.provinceName,
            //               Addr = a.Addr,
            //               CreateName = a.CreateName,
            //               CreateTime = a.CreateTime,
            //               UpdateName = a.UpdateName,
            //               UpdateTime = a.UpdateTime,
            //               IsDel = a.IsDel,
            //               RoleName = d.RoleName ?? "未分配角色",
            //           };

            var linq = from a in user
                       join b in province on a.provinceId equals b.provinceId
                       join c in accountrole on a.UserId equals c.UserId into userRoles
                       from c in userRoles.DefaultIfEmpty() // 左外连接用户和角色关联表
                       join d in role on c.RoleId equals d.RoleId into wang
                       from d in wang.DefaultIfEmpty() // 左外连接角色详情表
                       select new UserDTO
                       {
                           UserId = a.UserId,
                           UserName = a.UserName,
                           PassWord = a.PassWord,
                           Sex = a.Sex,
                           provinceId = a.provinceId,
                           provinceName = b.provinceName,
                           Addr = a.Addr,
                           CreateName = a.CreateName,
                           CreateTime = a.CreateTime,
                           UpdateName = a.UpdateName,
                           UpdateTime = a.UpdateTime,
                           IsDel = a.IsDel,
                           RoleName = d.RoleName ?? "未分配角色", // 处理可能为空的角色名
                       };

            var queryResult = linq.OrderByDescending(x => x.UserId)
                       .Skip((request.PageIndex - 1) * request.PageSize)
                       .Take(request.PageSize)
                       .ToList();

            // 使用字典合并相同用户的角色
            var mergedData = new Dictionary<int, UserDTO>();

            foreach (var item in queryResult)
            {
                //判断是否已经存在用户信息 wang 临时变量  TryGetValue避免在字典中查找不存在的用户(UserId)时抛出异常
                if (!mergedData.TryGetValue(item.UserId, out var wang))
                {
                    wang = new UserDTO
                    {
                        UserId = item.UserId,
                        UserName = item.UserName,
                        PassWord = item.PassWord,
                        Sex = item.Sex,
                        provinceId = item.provinceId,
                        provinceName = item.provinceName,
                        Addr = item.Addr,
                        CreateName = item.CreateName,
                        CreateTime = item.CreateTime,
                        UpdateName = item.UpdateName,
                        UpdateTime = item.UpdateTime,
                        IsDel = item.IsDel,
                        RoleName = item.RoleName
                    };
                    mergedData[item.UserId] = wang;
                }
                else
                {
                    wang.RoleName += "、" + item.RoleName; //合并已存在的信息
                }
            }

            res.ToTaCount = linq.Count();
            res.ToTaPage = (int)Math.Ceiling(res.ToTaCount * 1.0 / request.PageSize);
            res.Message = "分页查询成功";
            res.PageData = mergedData.Values.ToList();

            return Task.FromResult(res);

           

        }
    }
}
